package com.xinggq.common.security;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;

/**
 * JWT用户详情类
 * 封装JWT token中的用户信息，实现Spring Security的UserDetails接口
 * 
 * @author xinggq
 * @since 2025/1/20
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class JwtUserDetails implements UserDetails {

    /**
     * 用户ID
     */
    private Long userId;

    /**
     * 用户名
     */
    private String username;

    /**
     * 租户ID
     */
    private Long tenantId;

    /**
     * 真实姓名
     */
    private String realName;

    /**
     * 邮箱
     */
    private String email;

    /**
     * JWT token
     */
    private String token;

    /**
     * 构造函数 - 基础信息
     */
    public JwtUserDetails(Long userId, String username, Long tenantId) {
        this.userId = userId;
        this.username = username;
        this.tenantId = tenantId;
    }

    /**
     * 构造函数 - 完整信息
     */
    public JwtUserDetails(Long userId, String username, Long tenantId, String realName, String email) {
        this.userId = userId;
        this.username = username;
        this.tenantId = tenantId;
        this.realName = realName;
        this.email = email;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // JWT认证不依赖角色权限，返回空集合
        return Collections.emptyList();
    }

    @Override
    public String getPassword() {
        // JWT认证不需要密码
        return null;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    /**
     * 转换为UserInfo对象
     */
    public com.xinggq.common.context.UserInfo toUserInfo() {
        com.xinggq.common.context.UserInfo userInfo = new com.xinggq.common.context.UserInfo();
        userInfo.setUserId(this.userId);
        userInfo.setUsername(this.username);
        userInfo.setTenantId(this.tenantId);
        userInfo.setRealName(this.realName);
        userInfo.setEmail(this.email);
        return userInfo;
    }
}